<template>
  <view class="chat-detail">
    <!-- 聊天消息列表 -->
    <scroll-view
      id="messageScrollView"
      class="message-list"
      scroll-y
      scroll-anchoring
      enhanced
      show-scrollbar="false"
      scroll-with-animation
      :scroll-into-view="scrollToMessageId"
      upper-threshold="50"
      @scrolltoupper="loadMoreMessages"
    >
      <view v-if="messages.length > 0" class="message-date-wrapper">
        <view class="message-date">{{ formatDate(messages[0].time) }}</view>
      </view>

      <view
        v-for="(item, index) in messages"
        :id="'msg-' + item.id"
        :key="item.id"
        class="message-item"
      >
        <!-- 日期分隔线 -->
        <view
          v-if="index > 0 && showDateDivider(item.time, messages[index - 1].time)"
          class="message-date-wrapper"
        >
          <view class="message-date">{{ formatDate(item.time) }}</view>
        </view>

        <!-- 消息内容 -->
        <view class="message" :class="{ 'message-self': item.isSelf }">
          <image class="avatar" :src="item.avatar || '/static/avatar.png'" mode="aspectFill" />
          <view class="message-content">
            <view v-if="isGroup && !item.isSelf" class="sender">{{ item.sender }}</view>
            <view class="content" :class="{ 'content-self': item.isSelf }">
              <text v-if="item.type === 'text'">{{ item.content }}</text>
              <image
                v-else-if="item.type === 'image'"
                :src="item.content"
                mode="widthFix"
                class="content-image"
                @tap="previewImage(item.content)"
              />
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <view class="input-wrapper">
        <textarea
          v-model="inputMessage"
          class="text-input"
          auto-height
          cursor-spacing="20"
          show-confirm-bar="false"
          placeholder="请输入消息"
          :maxlength="500"
          @confirm="sendTextMessage"
        />

        <view class="input-actions">
          <view class="emoji-btn" @tap="toggleEmojiPanel">
            <wd-icon name="emoji" size="24px" color="#666" />
          </view>
          <view v-if="inputMessage.trim()" class="send-btn" @tap="sendTextMessage">发送</view>
          <view v-else class="more-btn" @tap="toggleToolbox">
            <wd-icon name="add-circle" size="24px" color="#666" />
          </view>
        </view>
      </view>

      <!-- 表情面板 -->
      <view v-if="showEmojiPanel" class="emoji-panel">
        <scroll-view scroll-x class="emoji-scroll">
          <view class="emoji-list">
            <view
              v-for="(emoji, index) in emojiList"
              :key="index"
              class="emoji-item"
              @tap="insertEmoji(emoji)"
            >
              {{ emoji }}
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 扩展功能栏 -->
      <view v-if="showToolbox" class="toolbox">
        <view class="tool-item" @tap="chooseImage">
          <view class="tool-icon">
            <wd-icon name="picture" size="24px" color="#07c160" />
          </view>
          <view class="tool-text">图片</view>
        </view>
        <view class="tool-item" @tap="chooseLocation">
          <view class="tool-icon">
            <wd-icon name="location" size="24px" color="#1296db" />
          </view>
          <view class="tool-text">位置</view>
        </view>
        <view class="tool-item" @tap="openDocument">
          <view class="tool-icon">
            <wd-icon name="document" size="24px" color="#ff9900" />
          </view>
          <view class="tool-text">文件</view>
        </view>
        <view class="tool-item" @tap="recordVideo">
          <view class="tool-icon">
            <wd-icon name="video" size="24px" color="#fd8732" />
          </view>
          <view class="tool-text">视频</view>
        </view>
        <view class="tool-item" @tap="sendRedPacket">
          <view class="tool-icon">
            <wd-icon name="red-packet" size="24px" color="#fa5151" />
          </view>
          <view class="tool-text">红包</view>
        </view>
        <view class="tool-item" @tap="startVoiceCall">
          <view class="tool-icon">
            <wd-icon name="phone" size="24px" color="#1aad19" />
          </view>
          <view class="tool-text">通话</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch, nextTick } from "vue";

// 获取路由参数
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const route = currentPage as any;
const chatId = (route.options?.id as string) || "";
const chatName = decodeURIComponent((route.options?.name as string) || "聊天");
const isGroup = route.options?.isGroup === "true";

// 设置页面标题
uni.setNavigationBarTitle({
  title: chatName,
});

// 消息输入
const inputMessage = ref("");
const showToolbox = ref(false);
const showEmojiPanel = ref(false);

// 消息列表和滚动控制
const messages = ref<any[]>([]);
const scrollToMessageId = ref("");
const scrollTop = ref(0);

// 表情列表
const emojiList = ref([
  "😊",
  "😂",
  "😍",
  "🤔",
  "😭",
  "👍",
  "🎉",
  "🔥",
  "❤️",
  "👋",
  "🙏",
  "🤝",
  "👏",
  "💪",
  "✅",
  "❌",
  "⭐",
  "🌈",
  "🍀",
  "🎁",
]);

// 模拟数据
function generateMockMessages() {
  const now = Date.now();
  const oneHour = 60 * 60 * 1000;
  const oneDay = 24 * oneHour;

  return [
    {
      id: "1",
      type: "text",
      content: "宗祠修缮工作已经完成了三分之一，预计下月完工",
      sender: "李家族长",
      avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
      isSelf: false,
      time: now - 5 * oneDay,
    },
    {
      id: "2",
      type: "text",
      content: "好的，谢谢族长的关心和支持",
      sender: "我",
      avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
      isSelf: true,
      time: now - 5 * oneDay + 5 * 60 * 1000,
    },
    {
      id: "3",
      type: "text",
      content: "这是今年的祭祖活动安排，请查收",
      sender: "李家族长",
      avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
      isSelf: false,
      time: now - 3 * oneDay,
    },
    {
      id: "4",
      type: "image",
      content: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
      sender: "李家族长",
      avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
      isSelf: false,
      time: now - 3 * oneDay + 1 * 60 * 1000,
    },
    {
      id: "5",
      type: "text",
      content: "收到，我会准时参加",
      sender: "我",
      avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
      isSelf: true,
      time: now - 3 * oneDay + 10 * 60 * 1000,
    },
    {
      id: "6",
      type: "text",
      content: "最近家谱整理有什么进展吗？",
      sender: "李家族长",
      avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
      isSelf: false,
      time: now - oneHour,
    },
  ];
}

// 加载消息
onMounted(() => {
  // 模拟数据
  messages.value = generateMockMessages();
  console.log(messages.value);
  // 延迟滚动到底部，等待渲染完成
  setTimeout(() => {
    scrollToBottom();
  }, 0);

  // 监听键盘弹出，自动滚动到底部
  // uni.onKeyboardHeightChange((res) => {
  //   if (res.height > 0) {
  //     scrollToBottom();
  //   }
  // });
});

// 发送文本消息
function sendTextMessage() {
  if (!inputMessage.value.trim()) return;

  const newMessage = {
    id: `msg-${Date.now()}`,
    type: "text",
    content: inputMessage.value,
    sender: "我",
    avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
    isSelf: true,
    time: Date.now(),
  };

  messages.value.push(newMessage);
  inputMessage.value = "";
  showToolbox.value = false;
  showEmojiPanel.value = false;

  // 立即滚动到底部
  scrollToBottom();

  // 模拟对方回复
  setTimeout(() => {
    const replyMessage = {
      id: `msg-${Date.now()}`,
      type: "text",
      content: isGroup ? "好的，我们会考虑你的建议" : "收到你的消息了，稍后回复你",
      sender: chatName,
      avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
      isSelf: false,
      time: Date.now(),
    };
    messages.value.push(replyMessage);
    // 再次滚动到底部
    scrollToBottom();
  }, 2000);
}

// 选择图片
function chooseImage() {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const newMessage = {
        id: `msg-${Date.now()}`,
        type: "image",
        content: res.tempFilePaths[0],
        sender: "我",
        avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
        isSelf: true,
        time: Date.now(),
      };

      messages.value.push(newMessage);
      showToolbox.value = false;
      scrollToBottom();
    },
  });
}

// 选择位置
function chooseLocation() {
  uni.chooseLocation({
    success: (res) => {
      console.log("选择的位置：", res);
      // 实际项目中应该发送位置消息
    },
  });
}

// 选择文件
function openDocument() {
  // 在实际项目中实现文件选择逻辑
  console.log("选择文件");
}

// 图片预览
function previewImage(url: string) {
  const imageUrls = messages.value.filter((msg) => msg.type === "image").map((msg) => msg.content);

  uni.previewImage({
    current: url,
    urls: imageUrls,
  });
}

// 滚动到底部
function scrollToBottom() {
  if (messages.value && messages.value.length > 0) {
    const lastMessage = messages.value[messages.value.length - 1];
    const lastId = "msg-" + lastMessage.id;

    // 延迟设置，确保DOM已更新
    setTimeout(() => {
      scrollToMessageId.value = lastId;
    }, 100);
  }
}

// 加载更多消息
function loadMoreMessages() {
  console.log("加载更多历史消息");
  // 实际项目中应该请求历史消息
}

// 切换工具箱显示
function toggleToolbox() {
  showToolbox.value = !showToolbox.value;
}

// 格式化消息日期
function formatDate(timestamp: number) {
  const date = new Date(timestamp);
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);

  if (date.toDateString() === today.toDateString()) {
    return "今天";
  } else if (date.toDateString() === yesterday.toDateString()) {
    return "昨天";
  } else {
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  }
}

// 判断是否显示日期分隔线
function showDateDivider(currentTime: number, prevTime: number) {
  const current = new Date(currentTime);
  const prev = new Date(prevTime);

  return (
    current.getDate() !== prev.getDate() ||
    current.getMonth() !== prev.getMonth() ||
    current.getFullYear() !== prev.getFullYear()
  );
}

// 切换表情面板
function toggleEmojiPanel() {
  showEmojiPanel.value = !showEmojiPanel.value;
  if (showEmojiPanel.value) {
    showToolbox.value = false;
  }
}

// 插入表情
function insertEmoji(emoji: string) {
  inputMessage.value += emoji;
}

// 录制视频
function recordVideo() {
  // 实际项目中实现视频录制逻辑
  console.log("录制视频");
}

// 发送红包
function sendRedPacket() {
  // 实际项目中实现红包功能
  console.log("发送红包");
}

// 开始语音通话
function startVoiceCall() {
  // 实际项目中实现通话功能
  console.log("开始通话");
}

// 监听消息列表变化，自动滚动到底部
watch(
  () => messages.value.length,
  () => {
    scrollToBottom();
  }
);
</script>

<style lang="scss">
.chat-detail {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #ededed;
  position: relative;
}

.message-list {
  flex: 1;
  height: calc(100vh - 120rpx); /* 减去输入框高度 */
  padding-bottom: 20rpx;
  overflow: auto; /* 添加自动滚动条 */
  display: flex;
  flex-direction: column;
}

/* 覆盖uni-app默认的scroll-view 100%高度 */
:deep(.uni-scroll-view) {
  height: auto !important;
}

:deep(.uni-scroll-view-content) {
  height: auto !important;
}

/* 直接使用选择器覆盖默认样式 */
.chat-detail scroll-view,
.chat-detail .uni-scroll-view,
.chat-detail .uni-scroll-view-content {
  height: auto !important;
}

.message-date-wrapper {
  display: flex;
  justify-content: center;
  margin: 20rpx 0;
}

.message-date {
  background-color: rgba(0, 0, 0, 0.1);
  color: #fff;
  font-size: 24rpx;
  padding: 4rpx 10rpx;
  border-radius: 8rpx;
  text-align: center;
}

.message {
  display: flex;
  margin-bottom: 24rpx;
}

.message-self {
  flex-direction: row-reverse;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
  margin: 0 16rpx;
}

.message-content {
  max-width: 60%;
}

.sender {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 6rpx;
  padding-left: 16rpx;
}

.content {
  background-color: #fff;
  border-radius: 4rpx;
  padding: 18rpx;
  font-size: 30rpx;
  word-break: break-all;
  position: relative;
  line-height: 40rpx;
  display: inline-block;

  &:before {
    content: "";
    position: absolute;
    left: -10rpx;
    top: 14rpx;
    width: 0;
    height: 0;
    border-top: 6rpx solid transparent;
    border-right: 10rpx solid #fff;
    border-bottom: 6rpx solid transparent;
  }
}

.content-self {
  background-color: #95ec69;
  color: #000;

  &:before {
    left: -10rpx;
    right: auto;
    border-right: 10rpx solid #95ec69;
    border-left: none;
  }
}

.content-image {
  max-width: 400rpx;
  border-radius: 4rpx;
}

.input-area {
  border-top: 1px solid #e6e6e6;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10;
  width: 100%;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 8rpx;
  padding: 8rpx;
  border: 1px solid #e0e0e0;
}

.text-input {
  flex: 1;
  font-size: 30rpx;
  min-height: 60rpx;
  max-height: 160rpx;
  padding: 10rpx;
}

.input-actions {
  display: flex;
  align-items: center;
}

.send-btn {
  background-color: #07c160;
  color: #fff;
  height: 60rpx;
  line-height: 60rpx;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  margin-left: 8rpx;
}

.emoji-panel {
  background-color: #fff;
  border-top: 1px solid #e6e6e6;
  padding: 20rpx 0;
  height: 220rpx;
}

.emoji-scroll {
  width: 100%;
  height: 100%;
}

.emoji-list {
  display: flex;
  flex-wrap: wrap;
  padding: 0 20rpx;
}

.emoji-item {
  width: 70rpx;
  height: 70rpx;
  font-size: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10rpx;
}

.toolbox {
  display: flex;
  padding: 30rpx 0;
  flex-wrap: wrap;
  background-color: #fff;
  border-top: 1px solid #e6e6e6;
}

.tool-item {
  width: 20%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 24rpx;
}

.tool-icon {
  width: 100rpx;
  height: 100rpx;
  background-color: #f8f8f8;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10rpx;
}

.tool-text {
  font-size: 24rpx;
  color: #777;
}
</style>
